<template>
  <div class="box">
    <header class="header">
      <van-nav-bar
        left-arrow
        title="选择地址"
        right-text="取消"
        @click-left="$router.back()"
        @click-right="onClickRight"
      />
    </header>
    <div class="cont">
      <van-address-list
        v-model="chosenAddressId"
        :list="list"
        default-tag-text="默认"
        @add="onAdd"
        @edit="onEdit"
        @select="reOrderDetail"
      />
    </div>
  </div>
</template>

<script>
import Vue from 'vue'
import { AddressList, NavBar } from 'vant'
import { getAddress, deleteAddress } from '../../api/index.js'

Vue.use(AddressList)
Vue.use(NavBar)

export default {
  data () {
    return {
      chosenAddressId: '1',
      list: []
    }
  },
  mounted () {
    // console.log(localStorage)
    getAddress({
      userId: localStorage.getItem('userId')
    }).then(data => {
      // console.log(data)
      if (data.data.state === 200) {
        // console.log(data)
        this.list = data.data.data.addData
        if (data.data.data.addData.length > 0) {
          let i = 0
          this.list.some((val, idx) => {
            i = idx
            return val.isDefault
          })
          this.chosenAddressId = this.list[i].addressId
        }
      }
    })
  },
  methods: {
    onClickRight () {
      if (this.$route.query.id) {
        this.$router.push('/orderDetail/' + this.$route.query.id)
      } else {
        this.$router.push('/setUserMsg')
      }
    },
    onAdd () {
      // Toast('新增地址')
      if (this.$route.query.id) {
        this.$router.push('/addAddress?id=' + this.$route.query.id)
      } else {
        this.$router.push('/addAddress')
      }
    },
    onEdit (item, index) {
      // Toast('编辑地址:' + index)
      // console.log(item, index)
      deleteAddress({
        userId: localStorage.getItem('id'),
        addressId: item.addressId
      })
      this.list.splice(index, 1)
    },
    reOrderDetail (item, index) {
      // console.log(item, index)
      if (this.$route.query.id) {
        this.$router.push('/orderDetail/' + this.$route.query.id + '?id=' + index)
      }
    }
  }
}
</script>

<style>
  .van-radio__icon--round{
    display: none;
  }
</style>
